from types import FunctionType
from collections import OrderedDict

from django.db.models import Q, Sum
from django.shortcuts import render
from django.http import JsonResponse

from web import models
from web.utils.group import get_choice_text, Option, get_search_group_condition
from web.utils.pager import Pagernation


def bottype_list(request, pk):
    list_display = [
        'bot_type',
        'bot_attack_count',
        'update_datetime'
    ]
    model_class = models.BotgateBotType
    # 配置组合搜索
    search_group = [
    ]
    search_group_list = []
    for option_object in search_group:
        search_group_list.append(option_object.get_queryset_or_tuple(request, model_class))
    # 获取组合搜索条件
    conn = get_search_group_condition(search_group, request)

    # 获取搜索条件
    search_list = [
        'bot_type__contains'
    ]
    keyword = request.GET.get("keyword", "").strip()
    con = Q()
    con.connector = "OR"
    if keyword:
        for item in search_list:
            con.children.append((item, keyword))
    obj = models.Botgate.objects.filter(id=pk).first()
    data_time = obj.create_datetime
    queryset = models.BotgateBotType.objects.filter(con).filter(**conn). \
        filter(create_datetime__year=data_time.year,
               create_datetime__month=data_time.month,
               create_datetime__day=data_time.day).order_by('-bot_attack_count')

    pager = Pagernation(request, queryset)
    # 1.处理表头
    header_list = []
    if list_display:
        for key_or_func in list_display:
            if isinstance(key_or_func, FunctionType):
                header_list.append(key_or_func(None, True))
            else:
                verbose_name = model_class._meta.get_field(key_or_func).verbose_name
                header_list.append(verbose_name)
    else:
        header_list.append(model_class._meta.model_name)
    # 2.处理表格内容
    data_list = queryset[pager.start:pager.end]
    body_list = []
    for row in data_list:
        tr_list = []
        if list_display:
            for key_or_func in list_display:
                if isinstance(key_or_func, FunctionType):
                    tr_list.append(key_or_func(row, False))
                else:
                    tr_list.append('' if getattr(row, key_or_func) == None else getattr(row, key_or_func))
        else:
            tr_list.append(row)
        body_list.append(tr_list)
    pager = Pagernation(request, queryset)
    context = {
        'body_list': body_list,
        'header_list': header_list,
        'pager': pager,
        'keyword': keyword,
        'search_group_row_list': search_group_list,
        'id': pk
    }
    return render(request, 'botgate_bottype_list.html', context)


def statistics_bottype(request):
    pk = request.GET.get('id')
    obj = models.Botgate.objects.filter(id=pk).first()
    date_time = obj.create_datetime
    queryset = models.BotgateBotType.objects.filter(create_datetime__year=date_time.year,
                                                    create_datetime__month=date_time.month,
                                                    create_datetime__day=date_time.day). \
        values('bot_type').annotate(ct=Sum('bot_attack_count')).order_by('-ct')
    data_dict = OrderedDict()
    total_count = 0
    for item in queryset:
        data_dict[item['bot_type']] = {'name': item['bot_type'], 'y': 0}
        total_count += item['ct']

    for item in queryset:
        data_dict[item['bot_type']]['y'] = round(item['ct'] / total_count * 100, 2)
    context = {
        'status': True,
        'data': list(data_dict.values())
    }

    return JsonResponse(context)
